package com.immyc.util;

import java.security.MessageDigest;
import java.util.Random;

/**
 * @Description:
 * @Author: mayc
 * @Date: 2019/04/24 13:44
 */
public class PasswordEncoder {

    public static final String generateNum(final int len) {
        final String str = "0,1,2,3,4,5,6,7,8,9";
        final String[] str2 = str.split(",");
        final Random rand = new Random();
        int index = 0;
        String randStr = "";
        for (int i = 0; i < len; ++i) {
            index = rand.nextInt(str2.length - 1);
            randStr += str2[index];
        }
        return randStr;
    }

    public static final String pwdRule(final String pwd, final String salt) {
        final String rule = pwd + salt;
        return md5(rule);
    }

    public static final String generate(final int len) {
        final String str = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        final String[] str2 = str.split(",");
        final Random rand = new Random();
        int index = 0;
        String randStr = "";
        for (int i = 0; i < len; ++i) {
            index = rand.nextInt(str2.length - 1);
            randStr += str2[index];
        }
        return randStr;
    }

    public static final String salt() {
        return generate(6);
    }

    public static final String md5(final String s) {
        final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            final byte[] btInput = s.getBytes();
            final MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            final byte[] md = mdInst.digest();
            final int j = md.length;
            final char[] str = new char[j * 2];
            int k = 0;
            for (final byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xF];
                str[k++] = hexDigits[byte0 & 0xF];
            }
            return new String(str).toLowerCase();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(final String[] args) {
        final String salt = salt();
        final String password = pwdRule("123456", "2fyijp");
        System.out.println(salt + "---" + password);
        //System.out.println(pwdValidate("123456", "x3m36l", "1739daaea1efef22af951229f4e69bd2"));
    }

    public static final boolean pwdValidate(final String pwd, final String salt, final String dpwd) {
        return pwdRule(pwd, salt).equals(dpwd);
    }
}
